import { Body, Controller, Delete, Get, Param, Post, Put, Query, Req } from '@nestjs/common';
import { UserService } from './user.service';
import R from 'src/common/dto/R.dto';
import { QueryUserDto } from './dto/query-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { ModifyPasswordDto } from './dto/modify-password.dto';
import { EncryptUtil } from 'src/utils/Encrypt.util';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  /**新增用户 */
  @Post('addUser')
  async addUser(@Body() updateUser: UpdateUserDto) {
    // 判断用户是否存在
    const isExist = await this.userService.findOne(updateUser.username);
    if (isExist) {
      return R.fail('用户已存在!');
    }
    return R.success(await this.userService.save(updateUser), '保存成功');
  }

  /**修改用户 */
  @Put('updateUser')
  async updateUser(@Body() updateUser: UpdateUserDto) {
    return R.success(await this.userService.save(updateUser), '修改成功');
  }

  /**
   * 获取所有用户
   */
  @Get('getUserList')
  async getUserList(@Query() getUserListDto: QueryUserDto) {
    let { users, total } = await this.userService.findAll(getUserListDto);
    const resUsers = users.map((user) => {
      const { password, ...userInfo } = user;
      return userInfo;
    });
    return R.success({
      users: resUsers,
      total,
    });
  }

  /**
   * 删除用户
   */
  @Delete('delete/:username')
  async deleteUser(@Param('username') username: string) {
    const user = await this.userService.findOne(username);
    if (!user) {
      return R.fail('用户不存在!');
    }

    if (user.username === 'admin') {
      return R.fail('超级管理员不能删除!');
    }

    return R.success(await this.userService.remove(user), '删除成功');
  }

  // 获取用户信息
  @Get('getUserInfo')
  async getUserInfo(@Req() req: { user: { username: string; sub: string } }) {
    const user = await this.userService.findOne(req.user.username);

    if (!user) {
      return R.fail('用户不存在');
    }
    // 移除密码
    const { password, ...userInfo } = user;
    return R.success(userInfo);
  }

  /** 修改密码 */
  @Put('modifyPassword')
  async updatePassword(@Body() body: ModifyPasswordDto, @Req() req: { user: { username: string; sub: string } }) {
    const user = await this.userService.findOne(req.user.username);

    const oldPassword = await EncryptUtil.decrypt(body.oldPassword);
    const newPassword = await EncryptUtil.decrypt(body.newPassword);

    if (user.password !== oldPassword) {
      return R.fail('旧密码错误');
    }
    if (user.password === newPassword) {
      return R.fail('新密码不能与旧密码相同');
    }

    user.password = newPassword;
    await this.userService.save(user);

    return R.success(null, '修改成功');
  }
}
